package pers.jing.android.helper.page

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Refresh
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import org.koin.compose.viewmodel.koinViewModel
import kotlin.math.min

/**
 * 手机屏幕页面, 主要用于显示手机屏幕信息
 * 缩放窗口大小之后, [Modifier.onSizeChanged]并不会被调用
 */
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun DeviceScreenPage(viewModel: DeviceViewModel = koinViewModel<DeviceViewModel>()) {
    viewModel.startRefreshScreenshot()
    val density = LocalDensity.current
    var screenImage = viewModel.screenImage.collectAsState()
    Box(
        modifier = Modifier.fillMaxSize(),
    ) {
        BoxWithConstraints(
            modifier = Modifier
                .align(Alignment.Center)
                .padding(vertical = 10.dp)
        ) {
            val imageWidth = screenImage.value.width
            val imageHeight = screenImage.value.height
            if (imageWidth > 0 && imageHeight > 0) {
                //目前只知道在这里重新计算显示高度, 暂时无其他方案
                val containerWidth = constraints.maxWidth
                val containerHeight = constraints.maxHeight
                // 计算等比缩放比例（取宽、高比例中的较小值，避免图片超出父容器）
                val scaleRatio = min(
                    containerWidth / imageWidth.toFloat(),
                    containerHeight / imageHeight.toFloat()
                )
                val imageDisplayWidth = (imageWidth * scaleRatio).toInt()
                val imageDisplayHeight = (imageHeight * scaleRatio).toInt()
                Image(
                    bitmap = screenImage.value,
                    contentDescription = "屏幕截图",
                    contentScale = ContentScale.Fit,
                    modifier = Modifier.size(
                        with(density) { imageDisplayWidth.toDp() },
                        with(density) { imageDisplayHeight.toDp() })
                        .pointerInput(Unit) {
                            //处理点击事件
                            detectTapGestures { offset ->
                                viewModel.tap(imageDisplayWidth, imageDisplayHeight,
                                    offset.x.toInt(), offset.y.toInt())
                            }
                        }.pointerInput(Unit) {
                            //处理滑动事件, 此处仅处理起点和终点
                            var startOffset: Offset? = null
                            var totalOffset: Offset = Offset.Zero
                            detectDragGestures(
                                onDragStart = { startOffset = it },
                                onDragEnd = {
                                    if (startOffset != null) {
                                        viewModel.swipe(imageDisplayWidth, imageDisplayHeight,
                                            Pair(startOffset!!.x.toInt(), startOffset!!.y.toInt()),
                                            Pair(startOffset!!.x.toInt() + totalOffset.x.toInt(),
                                                startOffset!!.y.toInt() + totalOffset.y.toInt()))
                                    }
                                    startOffset = null
                                    totalOffset = Offset.Zero
                                },
                                onDragCancel = {

                                },
                                onDrag = {_, offset ->
                                    //此处是相对移动距离
                                    totalOffset += offset
                                }
                            )
                        },

                    )
            }
        }
    }
}